package org.dragonnova.meetingapp.app.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.xys.libzxing.zxing.activity.CaptureActivity;

import org.dragonnova.meetingapp.R;
import org.dragonnova.meetingapp.utils.LogUtil;
import org.dragonnova.meetingapp.utils.WifiAutoConnectUtil;

import java.util.ArrayList;
import java.util.Arrays;

public class RouterActivity extends AppCompatActivity {

    private ArrayList<String> mMessage;
    private WifiManager mWifiManager;
    private WifiAutoConnectUtil mWifiAutoConnectUtil;
    private ConnectivityManager mConnectivityManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_router);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        Button router_bt_scan = (Button) findViewById(R.id.router_bt_scan);
        Button router_bt_set = (Button) findViewById(R.id.router_bt_set);

        router_bt_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent openCameraIntent = new Intent(RouterActivity.this, CaptureActivity.class);
                startActivityForResult(openCameraIntent, 0);
            }
        });

        router_bt_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        mWifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        mWifiAutoConnectUtil = new WifiAutoConnectUtil(mWifiManager);

        NetReceiver netReceiver = new NetReceiver();
        registerReceiver(netReceiver, getNetFilter());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            if (!TextUtils.isEmpty(scanResult)) {
                String[] msg = scanResult.split(" ");
                if (msg.length == 3) {
                    mMessage = new ArrayList<>(Arrays.asList(msg));
                    mWifiAutoConnectUtil.connect(mMessage.get(0), mMessage.get(1), WifiAutoConnectUtil.WifiCipherType.WIFICIPHER_WPA);
                } else {
                    Toast.makeText(this, getString(R.string.prompt_wrong_qr_msg), Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, getString(R.string.prompt_wrong_qr_msg), Toast.LENGTH_SHORT).show();
            }
        }
    }


    /**
     * 全局广播
     */
    private class NetReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
            WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                if (networkInfo != null && networkInfo.isConnected()) {
                    ///网络连接
                    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        //wifi连接
                        LogUtil.eee("NET_TYPE_WIFI");
                    } else if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                        //有线网络
                        LogUtil.eee("NET_TYPE_ETHERNET");
                    } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        //3g网络
                        LogUtil.eee("NET_TYPE_MOBILE");
                    }
                } else if (networkInfo != null && networkInfo.isAvailable()) {
                    //有网络，但是没有连接
                    LogUtil.eee("NET_TYPE_AVAILABLE");
                } else {
                    //其他状态
                    LogUtil.eee("NET_TYPE_NOT_AVAILABLE");
                }
            } else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);
                switch (wifiState) {
                    case WifiManager.WIFI_STATE_DISABLED:
                        LogUtil.e("WifiState", "DISABLED");
                        break;
                    case WifiManager.WIFI_STATE_DISABLING:
                        break;
                    case WifiManager.WIFI_STATE_ENABLED:
                        LogUtil.e("WifiState", "ENABLED");
                        break;
                    case WifiManager.WIFI_STATE_ENABLING:
                        break;
                    case WifiManager.WIFI_STATE_UNKNOWN:
                        break;
                }
            } else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (null != parcelableExtra) {
                    NetworkInfo info = (NetworkInfo) parcelableExtra;
                    switch (info.getState()) {
                        case CONNECTED:
                            // 网络已连接
                            LogUtil.e("WifiState", "CONNECTED");
                            if (mMessage != null && mMessage.size() == 3) {
                                if (wifiInfo.getSSID() != null && (wifiInfo.getSSID().equalsIgnoreCase("\"" + mMessage.get(0) + "\"") || wifiInfo.getSSID().equalsIgnoreCase(mMessage.get(1)))) {
                                    LogUtil.e("WifiState", "CORRECT");
                                    Intent webIntent = new Intent(RouterActivity.this, WebActivity.class);
                                    webIntent.putExtra("ip",mMessage.get(2));
                                    startActivity(webIntent);
                                } else {
                                    //连接的不是制定的网络
                                    LogUtil.e("WifiState", "INCORRECT");
                                }
                            }
                            break;
                        case CONNECTING:
                            LogUtil.e("WifiState", "CONNECTING");
                            break;
                        case DISCONNECTED:
                            LogUtil.e("WifiState", "DISCONNECTED");
                            break;
                        case DISCONNECTING:
                            LogUtil.e("WifiState", "DISCONNECTING");
                            break;
                        case SUSPENDED:
                            LogUtil.e("WifiState", "SUSPENDED");
                            break;
                        case UNKNOWN:
                            LogUtil.e("WifiState", "UNKNOWN");
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    }

    private IntentFilter getNetFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        return filter;
    }
}
